<template>
  <page-header-wrapper>
    <page-tab-list>
      <SearchBox @search="search" @exportData="exportData"></SearchBox>
    </page-tab-list>
    <a-card :bordered="false">
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <a-radio-group :defaultValue="-1" v-model="queryParam.status" @change="onOptionChange">
          <a-radio-button v-for="(item, index) in options" :key="index" :value="item.value">
            {{ item.title }}
          </a-radio-button>
        </a-radio-group>

        <a-dropdown v-if="userInfo.info.type === 'supplier'">
          <a-menu slot="overlay">
            <!--            <a-menu-item @click="batch('remove')">批量删除</a-menu-item>-->
            <a-menu-item @click="batch('export')">批量导出</a-menu-item>
            <a-menu-item @click="sendData">批量发货</a-menu-item>
          </a-menu>
          <a-button> 批量操作 </a-button>
        </a-dropdown>
      </div>
      <!-- <a-spin :spinning="spinning">
        <ListTable ref="listTable" :list_th="list_th" :pagaData="pagaData" @triggerAction="listActions"> </ListTable>
      </a-spin> -->
      <OrderListTable ref="table" :orderList="pagaData" @triggerAction="triggerAction"></OrderListTable>
      <div style="float: right">
        <Pagination v-model="pageParams.page" :total="totalCount" show-less-items />
      </div>
    </a-card>
    <SendModal
      :visible.sync="isShowSendModal"
      :expressList="expressList"
      :orderId="orderId"
      :goodsSendType="0"
      :orderInfo="orderInfo"
      @onAfterClose="onAfterClose"
    ></SendModal>
    <SendAllModal
      :visible.sync="isShowAllSendModal"
      :expressList="expressList"
      :orderId="orderId"
      :orderInfo="orderInfo"
      :xlsx="xlsx"
      @onAfterClose="onAfterClose"
    ></SendAllModal>
    <AddressModal
      ref="addressModal"
      v-if="isShowAddressModal"
      :visible.sync="isShowAddressModal"
      :orderId="orderId"
      @onAfterClose="onAfterClose"
    ></AddressModal>
    <OrderPrintModal :visible.sync="isShowPrintModal" :order="orderInfo"></OrderPrintModal>

    <toolsExport
      ref="toolsExport"
      :params="exportParams"
      :search="queryParam"
      :exportUrl="exportUrl"
      :menus="export_list"
    ></toolsExport>
  </page-header-wrapper>
</template>

<script>
import SendModal from './components/SendModal'
import SendAllModal from './components/SendAllModal'
import AddressModal from './components/AddressModal'
import OrderPrintModal from './components/OrderPrint'
import NoBorderRadio from '@/components/NoBorderRadio/NoBorderRadio'
import SearchBox from './components/SearchBox'

import zhCN from 'ant-design-vue/lib/locale-provider/zh_CN'
import moment from 'moment'
import { Pagination } from 'ant-design-vue'
import ListTable from './components/ListTable'
import OrderListTable from './components/OrderListTable.vue'
import toolsExport from '@/components/tools/tools-export'
import { purchaseOrderInfo } from '@/api/purchase/supplier'
import { submitOrder } from '@/api/purchase/stbz'

import {
  purchaseOrderList as getOrderList,
  checkApply,
  cancleOrder,
  setComments,
  orderConfirm,
  orderClerk,
  orderTable,
  orderEdit,
  supplierOrderDel,
  supplierSendTypeList,
  supplierSendTypeRefundList,
} from '@/api/purchase/purchase'
import { orderPrint } from '@/api/order'
export default {
  name: 'OrderList',
  components: {
    ListTable,
    Pagination,
    SendModal,
    AddressModal,
    OrderPrintModal,
    NoBorderRadio,
    SearchBox,
    OrderListTable,
    toolsExport,
    SendAllModal,
  },
  data() {
    return {
      options: [
        {
          title: '全部',
          value: -1,
        },
        {
          title: '待发货',
          value: 0,
        },
        {
          title: '待收货',
          value: 1,
        },
        {
          title: '已完成',
          value: 2,
        },
      ],
      spinning: false,
      expressList: [],
      list_th: [
        { type: 'list', title: '商品信息', span: 4 },
        { type: 'list', title: '单价/数量', span: 3 },
        { type: 'list', title: '运费/优惠', span: 2 },
        { type: 'list', title: '订单金额', span: 2 },
        { type: 'list', title: '买家/配送方式', span: 3 },
        { type: 'list', title: '商城/下单时间', span: 3 },
        { type: 'list', title: '订单状态', span: 2 },
        {
          type: 'list',
          title: '操作',
          span: 3,
          actions: ['编辑', '发货', '取消', '核销', '确认收货', '订单打印', '小票打印', '添加备注', '移入回收站'],
        },
      ],
      activeKey: '1',
      locale: zhCN,
      ranges: {
        一月内: () => [moment().startOf('day').subtract(1, 'month'), moment()],
        昨天: () => [moment().startOf('day').subtract(1, 'days'), moment().endOf('day').subtract(1, 'days')],
        最近一周: () => [moment().startOf('day').subtract(1, 'weeks'), moment()],
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      queryParam: {
        // 订单号
        // 商品名称
        // 手机号
      },
      selectDate: {},
      totalCount: 0,
      pageParams: {
        page: 1,
        limit: 10,
      },
      pagaData: [],
      remark: '',
      isShowSendModal: false,
      isShowAllSendModal: false,
      isShowAddressModal: false,
      orderId: '',
      isShowPrintModal: false,
      orderInfo: null,

      export_list: [],
      exportUrl: '',
      exportParams: {
        order_type: 1,
      },
      supplier_id: 0,
      xlsx: '',
      is_stbz: false,
    }
  },
  watch: {
    currentPage() {
      this.getOrderListData()
    },
  },
  created() {
    this.getOrderListData()

    this.exportUrl = purchaseOrderInfo()
  },
  activated() {},
  computed: {
    currentPage() {
      return this.pageParams.page || 1
    },
    userInfo() {
      return this.$store.state.user
    },
  },
  filters: {},
  methods: {
    supplierOrderDel(order_id) {
      this.$confirm({
        title: '提示',
        content: '是否执行此次操作？',
        onOk: () => {
          supplierOrderDel({
            order_id,
          }).then((res) => {
            if (!res.code) {
              this.pageParams.page = 1
              this.$message.success(res.msg)
              return
            }

            this.$message.error(res.msg)
          })
        },
        onCancel() {},
      })
    },

    batch(type) {
      let { selectedRowKeys } = this.$refs.table,
        ids
      if (!selectedRowKeys.length) {
        this.$message.error('至少选择一条数据！')
        return
      }

      switch (type) {
        case 'remove':
          ids = selectedRowKeys.map((el) => el.id).join(',')
          this.supplierOrderDel(ids)
          break

        case 'send':
          ids = selectedRowKeys
            .filter((el) => parseInt(el.status) === 0)
            .map((el) => el.id)
            .join(',')

          if (!ids) {
            this.$message.error('没有符合条件的数据！')
            return
          }

          this.orderId = ids
          this.orderInfo = null
          this.isShowAllSendModal = true
          break

        case 'export':
          this.exportParams.order_id = selectedRowKeys.map((el) => el.id).join(',')
          this.exportParams.supplier_id = this.supplier_id
          this.$refs.toolsExport.visible = true
          break
      }
    },
    sendData() {
      this.isShowAllSendModal = true
    },
    exportData() {
      this.exportParams.supplier_id = this.supplier_id
      this.$refs.toolsExport.visible = true
    },
    // 点击按钮触发
    triggerAction(data) {
      let { type, order } = data
      switch (type) {
        case 'detail': //详情
          this.$router.push({
            path: '/saas/supplierPurchaseGoods/purOrderDetail',
            query: { id: order.order_no, order_type: order.order_type },
          })
          break
        case 'deliver': //发货
          if (this.is_stbz) {
            this.$confirm({
              title: '提示',
              content: '是否确认发货？',
              onOk: () => {
                this.stbzSubmitOrder(order)
              },
              onCancel() {},
            })
          } else {
            this.orderId = order.id
            this.orderInfo = order
            this.isShowSendModal = true
          }
          break
        case 'cancle': //取消
          this.$confirm({
            title: '提示',
            content: '是否取消该订单？',
            onOk: () => {
              this.cancleOrder(order.id)
            },
            onCancel() {},
          })

          break
        case 'agree': //同意取消
          this.checkApply(1, order.id)
          break
        case 'refuse': //拒绝取消
          this.checkApply(0, order.id)
          break
        case 'order_print': //打印订单
          this.orderInfo = row
          this.isShowPrintModal = true
          break
        case 'order_receipts_print': //打印小票
          this.orderPrint(order)
          break
        case 'order_remark': //添加备注
          this.orderRemark(row)
          break
        case 'order_recycle': //移入回收站
          this.orderRecycle(row)
          break
        case 'order_address': //修改地址
          this.orderId = row.id
          this.isShowAddressModal = true
          break
        default:
          break
      }
    },
    async stbzSubmitOrder(order) {
      const hide = this.$message.loading('处理中...')
      const res = await submitOrder({ ...order, pifa: true })
      hide()
      if (res.code == 0) {
        this.$message.success('操作成功')
      }
    },
    // 点击搜索按钮
    search(e) {
      console.log(e)
      this.queryParam = e
      this.getOrderListData(true)
    },
    // listActions(name, row, reason) {
    //   switch (name) {
    //     case 'order_edit': //编辑
    //       this.$router.push({ path: '/order/order-details', query: { order_id: row.id } })
    //       break
    //     case 'order_send': //发货
    //       this.orderId = row.id
    //       this.orderInfo = row
    //       this.isShowSendModal = true
    //       break
    //     case 'order_cancel': //取消
    //       this.cancel(row, 1, 1, reason)
    //       break
    //     case 'order_cancel_0': //取消
    //       this.cancel(row, 0, 0, reason)
    //       break
    //     case 'order_cancel_1': //取消
    //       this.cancel(row, 1, 0, reason)
    //       break
    //     case 'order_cancel_verification': //核销
    //       this.clerk(row.id)
    //       break
    //     case 'order_confirm': //确认收货
    //       this.confirm(row.id)
    //       break
    //     case 'order_print': //打印订单
    //       console.log(name)
    //       this.orderInfo = row
    //       this.isShowPrintModal = true
    //       // this.orderTable(row)
    //       break
    //     case 'order_receipts_print': //打印小票
    //       console.log(name)
    //       this.orderPrint(row)
    //       break
    //     case 'order_remark': //添加备注
    //       this.orderRemark(row)
    //       break
    //     case 'order_recycle': //移入回收站
    //       console.log(name)
    //       this.orderRecycle(row)
    //       break
    //     case 'order_address': //修改地址
    //       this.orderId = row.id
    //       this.isShowAddressModal = true
    //       break
    //     case 'apply_0': //拒绝取消
    //       console.log(name)
    //       break
    //     case 'apply_1': //同意取消
    //       console.log(name)
    //       break
    //     default:
    //       break
    //   }
    // },
    clerk(order_id) {
      var params = {
        order_id: order_id,
      }
      const hide = this.$message.loading('核销中...', 0)
      orderClerk(params)
        .then((res) => {
          console.log(res)
          hide()
          if (res.code !== 0) {
            this.$error({
              content: res.msg,
            })
          } else {
            this.$message.success('成功')
            this.getOrderListData()
          }
        })
        .catch((err) => {
          this.$message.error(err.message)
        })
    },
    confirm(order_id) {
      var params = {
        order_id: order_id,
      }
      const hide = this.$message.loading('确认中...', 0)
      orderConfirm(params)
        .then((res) => {
          console.log(res)
          hide()
          if (res.code !== 0) {
            this.$error({
              content: res.msg,
            })
          } else {
            this.$message.success('确认成功')
            this.getOrderListData()
          }
        })
        .catch((err) => {
          this.$message.error(err.message)
        })
    },
    onOptionChange(val) {
      console.log(val)
      let status = val.target.value
      if (status == '7') {
        this.queryParam.is_recycle = 1
        this.queryParam.status = ''
        this.getOrderListData()
      } else {
        this.queryParam.is_recycle = 0
        this.queryParam.status = status
        this.getOrderListData()
      }
    },
    orderRemark(row) {
      const h = this.$createElement
      this.$confirm({
        icon: '<>',
        closable: true,
        width: 540,
        title: '添加备注信息',
        maskClosable: true,
        content: h('div', {}, [
          h('a-textarea', {
            props: {
              placeholder: '填写备注',
              autoSize: { minRows: 4, maxRows: 6 },
            },
            on: {
              change: (val) => {
                this.remark = val.target.value
              },
            },
          }),
        ]),
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
          const hide = this.$message.loading('取消中...', 0)
          setComments({
            order_id: row.id,
            seller_comments: this.remark,
          }).then((res) => {
            hide()
            if (res.code !== 0) {
              this.$error({
                content: res.msg,
              })
            } else {
              this.$message.success(res.msg)
              this.getOrderListData()
            }
          })
        },
      })
    },
    orderRecycle(row) {
      this.$confirm({
        icon: '<>',
        closable: true,
        width: 540,
        title: '是否移入回收站',
        maskClosable: true,
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
          const hide = this.$message.loading('取消中...', 0)
          orderEdit({
            order_id: row.id,
            is_recycle: 1,
          }).then((res) => {
            hide()
            if (res.code !== 0) {
              this.$error({
                content: res.msg,
              })
            } else {
              this.getOrderListData(true)
              this.$message.success(res.msg)
            }
          })
        },
      })
    },
    getOrderListData(flag) {
      this.spinning = true
      if (flag) {
        this.pageParams.page = 1
      }
      let params = {
        ...this.queryParam,
        ...this.pageParams,
        type: 0,
      }
      supplierSendTypeList(params).then((res) => {
        console.log(res)
        if (res.code === 0) {
          this.expressList = res.data.express
          this.pagaData = res.data.list
          this.totalCount = res.data.count
          this.export_list = res.data.export_list
          this.supplier_id = res.data.supplier_id
          this.$refs.table.selectedRowKeys = []
          this.xlsx = res.data.xlsx
          this.is_stbz = res.data.is_stbz
        } else {
          that.$message.error(res.msg)
        }
        this.spinning = false
      })
    },
    resetSearchForm() {
      this.queryParam = {
        dateStart: moment(new Date()),
        dateEnd: moment(new Date()),
      }
    },
    moment,
    onAfterClose() {
      this.getOrderListData()
    },
    orderPrint(order) {
      const hide = this.$message.loading('提交中...', 0)
      orderPrint({
        order_id: order.id,
        type: 2,
      }).then((res) => {
        hide()
        if (res.code !== 0) {
          this.$error({
            content: res.msg,
          })
        } else {
          this.$message.success(res.msg)
        }
      })
    },
    orderTable(order) {
      const hide = this.$message.loading('提交中...', 0)
      orderTable({
        order_id: order.id,
      }).then((res) => {
        hide()
        if (res.code !== 0) {
          this.$error({
            content: res.msg,
          })
        } else {
          this.getOrderListData()
          this.$message.success(res.msg)
        }
      })
    },
    // 审核订单取消申请
    async checkApply(stuats, order_id) {
      // 0不通过 1通过
      const res = await checkApply({ delete_pass: stuats, order_id })
      if (res.code == 0) {
        this.getOrderListData()
      }
    },
    // 点击取消订单
    async cancleOrder(order_id) {
      const res = await cancleOrder({ order_id, delete_pass: 1 })
      if (res.code == 0) {
        this.$message.success(res.msg)
        this.getOrderListData()
      } else {
        this.$message.error(res.msg)
      }
    },
  },
}
</script>
<style lang="less" scoped>
/deep/.ant-card-head {
  border-bottom: none;
}
.top_card {
  /deep/.ant-card-body {
    padding-bottom: 0;
  }
  /deep/.ant-tabs-bar {
    margin-bottom: 0;
    border-bottom: 1px solid #fff;
  }
}
.over_e {
  width: 192px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>
